//
//  ST_RegisterMonitor.swift
//  btvideo
//
//  Created by mac on 2021/3/16.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import KeychainAccess
import SwiftyUserDefaults
import RxCocoa
import RxSwift
import RealmSwift
import SwifterSwift
import SwiftyJSON

class ST_RegisterMonitor: NSObject {
    
    
    
//MARK: - init
    static let shared = ST_RegisterMonitor()
    
    /// 步骤上报
    let logger = ST_RegisterStepMonitor()
    
    private override init() {
        super.init()
        binding()
    }
    
    /// 当前走注册流程   key = accid  value = true注册  ，false登录
    private(set) var current_account_register_step_type_map = [String:Bool]()
    
    /// 注册页面的NavigationController
    weak var from_navigation_controller:UINavigationController?
    
    /// 选择性别之前的步骤
    fileprivate let route_classes_before_gender_picked = [ST_QuickStartProfileController.self]
    
    /// SexPreferenceViewController.self 取消了
    
    /// 选择了男性步骤
    fileprivate let route_classes_male_picked = [ST_NearbyGirlsRegisterController.self, ST_RegisterFriendForViewController.self, ST_SeekPreferenceViewController.self, ST_ParentStyleRegisterController.self, ST_ChildStyleRegisterController.self, ST_RecommendStyleRegisterViewController.self, ST_TicketViewController.self, ST_StartHomeViewController.self]
    
    /// 选择了女性
    fileprivate let route_classes_female_picked = [ST_NearbyGirlsRegisterController.self,  ST_RegisterFriendForViewController.self, ST_SeekPreferenceViewController.self, ST_ParentStyleRegisterController.self,ST_ChildStyleRegisterController.self,ST_RecommendStyleRegisterViewController.self,ST_StartHomeViewController.self]
    
    /// 步骤监听
    fileprivate let next_step_behavior = BehaviorRelay<ST_RegisterRouteWrapper?>(value: nil)
    
    /// 跳转
    fileprivate let push_observer = PublishSubject<UIViewController>()
    
    /// 当前正在注册的ID
    fileprivate let current_regist_i_d_key = "currentRegistID334"
    /// 当前的步骤
    fileprivate let register_step_class_string_key = "registerStepClassString334"
    
    /// 忽略保存的步骤
    fileprivate let ignore_step_class:Set<String> = [String(describing: ST_ChildStyleRegisterController.self),String(describing: ST_QuickStartProfileController.self)]
    
    /* 临时保存数据
     key = class Type String
     */
    var step_parameters = [String:Any]()
    
    var disposebag = DisposeBag()
    
    
    
    fileprivate lazy var testBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.cornerRadius = 22
        
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        
        //        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.disabled)
      
        
        control.setTitleColorForAllStates(UIColor.white)
        
        control.setTitleColor(UIColor.white, for: UIControl.State.disabled)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        
        return control
    }()
}

extension ST_RegisterMonitor{
    
    fileprivate func binding(){
        
        self.push_observer.subscribe(onNext: { vc in
            
            let vcClass = NSStringFromClass(type(of: vc))
            
            print("ST_RegisterMonitor push_observer save defaults \(vcClass) ")
            
            
            if ST_RegisterMonitor.shared.ignore_step_class.contains(where: { vcClass.contains($0)  }) == false{
                
                UserDefaults.standard.setValue( vcClass , forKey: ST_RegisterMonitor.shared.register_step_class_string_key)
                
                UserDefaults.standard.synchronize()
                
            }
            
            ST_RegisterMonitor.shared.from_navigation_controller?.pushViewController(vc, animated: true)
            
        }).disposed(by: disposebag)
        
        
        
        self.next_step_behavior.skip(1).subscribe(onNext: {[weak self] wrapper in
            
            
            guard let account = self?.regist_response_account() else{
                return
            }
            
            /// 流程跳转下一步
            if let wp = wrapper{
                
                
                print("ST_RegisterMonitor receivedWrapper \(wp.vc) parameters = \(String(describing: wp.parameters))")
                
                if let param = wp.parameters{
                    
                    
                    if  let jsonDict = JSON(param).dictionary{
                        
                        self?.modify_register_value(dict: jsonDict)
                        
                    }
//                    改变用户喜欢的类型接口使用 PH.selectedFeatureListApi 其他使用 PH.newRegisterInfoApi
                    if param.keys.contains("features"){
                        self?.setUserRegister(api: PH.selectedFeatureListApi,param: param, wrapper: wp)
                    }else{
                        self?.setUserRegister(param: param, wrapper: wp)
                    }
                }else{
                    self?.receivedWrapper(wrapper: wp)
                }
            }else{
                
                switch account.registerStep {
                
                case .longer:
                    
                    
                    /// 长注册流程才会使用LOT 文件  懒加载
                    ST_SwiftConst.shared.load_lot_base_image()
                    
                    if let firstClass = self?.route_classes_before_gender_picked.first{
                        
                        self?.push_observer.onNext(firstClass.init())
                        
                    }
                case .shorter:
                 
                    self?.push_observer.onNext(ST_QuickStartProfileController())
                }
            }
            
        }).disposed(by: disposebag)
        
    }
    
    /// 当前跳转路由
    fileprivate func current_route_classes()->[UIViewController.Type]{
        
        var routeClasses = [UIViewController.self]
        
        guard let sex = regist_response_account()?.userinfo?.sex else {
            return routeClasses
        }
        
        switch sex{
        case .female:
            routeClasses = self.route_classes_female_picked
            
            print("ST_RegisterMonitor female routeClasses ")
            
        case .male:
            routeClasses = self.route_classes_male_picked
            
            print("ST_RegisterMonitor male routeClasses ")
        default:
            routeClasses = self.route_classes_before_gender_picked
            
            print("ST_RegisterMonitor male route_classes_before_gender_picked ")
        }
        
        return routeClasses
    }
    
    fileprivate func modify_register_value(dict:[String:JSON]){
        
        
        print("ST_RegisterMonitor start  modify_register_value \(dict) ")
        
        let realm = try! Realm()
        
        guard let key = UserDefaults.standard.string(forKey: self.current_regist_i_d_key),let account = realm.objects(ST_BTAccountInfo.self).filter("accid = %@", key).first else{
            return
        }
        
        if let genderValue = dict["gender"]{
            
            try! realm.write({
                account.userinfo?.gender = genderValue.intValue
            })
            
        }
        
        if let nickname = dict["nickname"]{
            
            try! realm.write({
                account.userinfo?.nickname = nickname.stringValue
            })
        }
        
    }
    
//    fileprivate func genderInitialization(sexValue:Int){
//
//        print("ST_RegisterMonitor start  genderInitialization \(sexValue) ")
//
//        let realm = try! Realm()
//
//        guard let key = UserDefaults.standard.string(forKey: self.current_regist_i_d_key),let account = realm.objects(ST_BTAccountInfo.self).filter("accid = %@", key).first else{
//            return
//        }
//
//        try! realm.write({
//            account.userinfo?.gender = sexValue
//        })
//
//        print("ST_RegisterMonitor end  genderInitialization \(sexValue) ")
//    }
    
    
    fileprivate func receivedWrapper(wrapper:ST_RegisterRouteWrapper){
        
        let wrapperClass = NSStringFromClass(type(of: wrapper.vc))
        
        guard let account = self.regist_response_account() else{
            return
        }
        
        switch account.registerStep {
        case .shorter:
            push_observer.onNext(ST_StartHomeViewController.init())
        case .longer:
         
            if wrapperClass.contains(String(describing: ST_ParentStyleRegisterController.self)) ,let p = wrapper.parameters{
                
                self.step_parameters.updateValue(p, forKey: wrapperClass)
                
            }
            
            
            let routeClasses = current_route_classes()
            
            /// 没有找到 当前class ，默认第一步
            var currentIdx : UInt = 0
            
            if let idx = routeClasses.firstIndex(where: { wrapperClass == NSStringFromClass($0) })?.uInt {
                
                currentIdx = idx + 1
            
                print("ST_RegisterMonitor found idx =  \(idx)")
                
            }
            
            
            
            print("ST_RegisterMonitor routeClasses count =  \(routeClasses.count)  curr = \(currentIdx)")
            
            guard let nextClass = routeClasses[safe:Int(currentIdx)] else{
                
                print("ST_RegisterMonitor 注册完成!! ")
                return
            }
            
            print("ST_RegisterMonitor push_observer next Class = \(nextClass)")
            
            push_observer.onNext(nextClass.init())
            
        }
        
    }
    
    
    fileprivate func setUserRegister(api:String = PH.newRegisterInfoApi,param:[String:Any],wrapper:ST_RegisterRouteWrapper){
        
        wrapper.vc.show_indeterminate_h_u_d()
        
        JVrequest(api,parameters: param,success: {(json) in
        
            wrapper.vc.hidden_indeterminate_h_u_d()
            
            self.receivedWrapper(wrapper: wrapper)
            
        },failure: { (code, str) in
                                    
            wrapper.vc.toast(text: str)
            
        })
        
    }
    
}

extension ST_RegisterMonitor{
    
    func set_up_test_btn(isFirstVC:Bool = true){
        
        
        
        if isFirstVC{
            
            let str = Defaults[.releaseAppApi] ? "👉测试" : "👉正式"
            testBtn.setTitleForAllStates(str)
        }else{
            testBtn.setTitleForAllStates("goback✌🏻")
        }
        
        testBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            
            self.revert_action(isFirstVC: isFirstVC)
            
        }).disposed(by: rx.disposeBag)
        
        UIApplication.shared.keyWindow?.addSubview(testBtn)
        
        testBtn.snp.makeConstraints { (make) in
            make.width.equalTo(80)
            make.height.equalTo(44)
            make.top.equalToSuperview().offset(10+statusBarHeight)
            make.left.equalToSuperview().offset(15)
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
            self.testBtn.removeFromSuperview()
        }
        
    }
    
    fileprivate func revert_action(isFirstVC:Bool = true){
        
        if isFirstVC{
            Defaults[.releaseAppApi] = !Defaults[.releaseAppApi]
            Defaults.synchronize()
        }else{
            clearRegister()
        }
        
        
        let alert = ST_BTHUDController.init(noticeText: "请重启设备生效!!")
        
        GlobalPresent(toController: alert)
        
        main_thread_execute(afterDelay: 1.5) {
            alert.dismiss(animated: false, completion: nil)
            exit(0)
        }
    }
    
    func welcome(regist:Bool){
        
//        注册
       if regist{
           
           next_step_behavior.accept(nil)
           
       }
//        登录欢迎回来
       else{
           
           clearRegister()
           
       }
    }
    
    func clearRegister(){
        
        
        print("ST_RegisterMonitor clearRegister ")
        
        UserDefaults.standard.removeObject(forKey: self.register_step_class_string_key)
        UserDefaults.standard.removeObject(forKey: self.current_regist_i_d_key)
        
        step_parameters.removeAll()
        
        
    }
    
    
    
    /**
     注册数据 临时保存
     */
    func regist_response_account()->ST_BTAccountInfo?{
        
        let realm = try! Realm()
        
        guard let key = UserDefaults.standard.string(forKey: self.current_regist_i_d_key),let account = realm.objects(ST_BTAccountInfo.self).filter("accid = %@", key).first else{
            return nil
        }
        
        return account
    }
    
    /// 重现注册步骤
    func login_root_controller_generator()->UIViewController{
        
        SCComponets.location_component.start_register_step_locate()
        
        var vc:UIViewController
        
        if let step = UserDefaults.standard.string(forKey: self.register_step_class_string_key){
            
            
//            let vcClass1 = NSClassFromString(step)
//
//            print("ST_RegisterMonitor vcClass1 \(vcClass1)")
            
            if let vcClass = NSClassFromString(step) as? UIViewController.Type{

                vc = vcClass.init()

                print("ST_RegisterMonitor vc is \(vcClass)")

                
        #if DEBUG
                            
                            main_thread_execute(afterDelay: 3) {
                                ST_RegisterMonitor.shared.set_up_test_btn(isFirstVC: false)
                            }
        #endif
                
            }else{

                print("ST_RegisterMonitor login_root_controller_generator \(step) not is a  UIViewController")

                vc = ST_SimilarLoginViewController()
            }
            
//            vc = ST_SimilarLoginViewController()
            
        }else{
            
            print("ST_RegisterMonitor login_root_controller_generator registerStepClass value nil ")
            
            
            vc = ST_SimilarLoginViewController()
        }
        
        let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
       
        nav.interactivePopGestureRecognizer?.isEnabled = false
        
        self.from_navigation_controller = nav
        
        return nav
    }
    
    func get_started(dict:[String:String],expectedHudController:UIViewController?){
        
        
        if  self.from_navigation_controller?.viewControllers.contains(where: { $0 is ST_WelcomeViewController }) == true{
            
            return
        }
        
        clearRegister()
        
        var parameters = dict
        
        PlayFeedBack()
        
        if let pas = UIPasteboard.general.string{
            
            print("来自soul 的方案:",pas)
            
            parameters.updateValue(pas, forKey: "invite")
        }
        
        expectedHudController?.show_indeterminate_h_u_d()
        
        JVrequest(PH.loginApi,parameters:parameters, success: { (json) in
        
            expectedHudController?.hidden_indeterminate_h_u_d()
            
            let dataJson = json["data"]
          
            print("登录返回信息:",dataJson)
            
//            Defaults[.BTRequirePay] = dataJson["tickets_switch"].intValue
            
            if let queueTime = dataJson["user_info"]["queue_time"].int , queueTime > 0{
                
                
                let vc = ST_WaitRegisterQueueController()
                    
                vc.delay_seconds = queueTime
                
                self.from_navigation_controller?.pushViewController(vc)
                
                return
            }
            
            
            let account = ST_BTAccountInfo()
            
            guard let userInfo = ST_BTUserinfo.deserialize(from: dataJson["user_info"].dictionaryObject) else{
                
                expectedHudController?.toast(text: "登录失败，请稍后再试,或联系我们")
                
                return
            }
                
            account.accid = userInfo.accid
            
            account.member_id = userInfo.member_id
            
            TIANKeychain[SC.tian_token_key] = dataJson["user_info"]["token"].stringValue
            
            account.userinfo = userInfo
            
            //            调研是否开启
//            BTProfileManager.shared.register_survey = RegisterSurveyModel.deserialize(from: dataJson["register_survey"].dictionaryObject)
            
//            let resourcePrefix = dataJson["qi_niu"]["prefix"][0].stringValue
//
//            Defaults[.QNResourcePrefix] = resourcePrefix
//            BAAS.forbidStatus = dataJson["extra_data"]["block_state"].intValue
            
            let tianRequireSignIn = dataJson["is_register_59"].boolValue
//            登录
            if !tianRequireSignIn {
                
                self.current_account_register_step_type_map.updateValue(false, forKey: account.accid)
                
                self.from_navigation_controller?.pushViewController(ST_WelcomeViewController.init(value: .login(account: account)))
                
            }
//            注册
            else{
                
                self.current_account_register_step_type_map.updateValue(true, forKey: account.accid)
                
                if let avatar = dict["regist_avatar"]{
                    account.userinfo?.avatar = avatar
                }
                
                if let nickname = dict["regist_nickname"]{
                    account.userinfo?.nickname = nickname
                }
                
                account.registerStep = dataJson["long_ticket_register"].boolValue ? .longer : .shorter
                
                let realm = try! Realm()
                try! realm.write {
                    realm.add(account, update: Realm.UpdatePolicy.all)
                }
                
                UserDefaults.standard.setValue(account.accid, forKey: self.current_regist_i_d_key)
                
                UserDefaults.standard.synchronize()
                
                /// 添加注册统计
                DispatchQueue.global().asyncAfter(deadline: .now() + 2, execute: {
                    SCComponets.location_component.push_location_of_registration_statistics()
                })
                
                self.from_navigation_controller?.pushViewController(ST_WelcomeViewController.init(value: .registry))
                
            }
            
            
            
            
        }, failure: { (code, err) in
            
            print("登录返回信息错误：",err)
            
            expectedHudController?.toast(text: err)
        })
        
    }
    
}


//MARK: - wrapper
struct ST_RegisterRouteWrapper {
    let vc:UIViewController
    let parameters:[String:Any]?
}


//MARK: - Protocol
protocol ST_RegisterRouteProtocol where Self : UIViewController{
    func pushNextRegisterController(parameters:[String:Any]?)
}

extension ST_RegisterRouteProtocol{
    
    func pushNextRegisterController(parameters: [String : Any]?){
        
        ST_RegisterMonitor.shared.next_step_behavior.accept(ST_RegisterRouteWrapper(vc: self, parameters: parameters))
        
    }
}

